package cn.rsa.aiwangren.advice;

import cn.rsa.aiwangren.util.Base64Util;
import cn.rsa.aiwangren.util.RSAUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;


/**
 * HTTP 实现类
 *
 * @author xiangtianlei
 * @date 2024/04/10
 */
@Configuration
public class DecryptHttpInputMessage implements HttpInputMessage {

    private HttpHeaders headers = null;
    private InputStream body = null;

    public DecryptHttpInputMessage() {
    }

    public DecryptHttpInputMessage(HttpInputMessage inputMessage, String privateKey, String charset, boolean showLog, int MAX_DECRYPT_BLOCK) throws Exception {

        if (StringUtils.isEmpty(privateKey)) {
            throw new IllegalArgumentException("privateKey is null");
        }

        this.headers = inputMessage.getHeaders();
        String content = new BufferedReader(new InputStreamReader(inputMessage.getBody()))
                .lines().collect(Collectors.joining(System.lineSeparator()));
        String decryptBody;
        Logger log = LoggerFactory.getLogger(this.getClass());
        if (content.startsWith("{")) {
            // 未加密
            log.info("Unencrypted without decryption:{}", content);
            decryptBody = content;
        } else {
            StringBuilder json = new StringBuilder();
            content = content.replaceAll(" ", "+");

            if (!StringUtils.isEmpty(content)) {
                String[] contents = content.split("\\|");
                for (String value : contents) {
                    value = new String(RSAUtil.decrypt(Base64Util.decode(value), privateKey, MAX_DECRYPT_BLOCK), charset);
                    json.append(value);
                }
            }
            decryptBody = json.toString();
            // 移除最前面和最后面的双引号
            decryptBody = decryptBody.replaceAll("^\"|\"$", "");
            if (showLog) {
                log.info("\nEncrypted data received：{}\nAfter decryption：{}", content, decryptBody);
            }
        }
        this.body = new ByteArrayInputStream(decryptBody.getBytes());
    }

    @Override
    public InputStream getBody() {
        return body;
    }

    @Override
    public HttpHeaders getHeaders() {
        return headers;
    }
}
